package com.zenagro.actions.loadfile;

import java.io.*;
import java.util.*;

import javax.inject.*;

import org.apache.commons.fileupload.*;
import org.openxava.actions.*;
import org.openxava.util.*;
import org.openxava.view.*;
import com.zenagro.utils.FileEntityUtils;

public class LoadFileAction extends ViewBaseAction implements INavigationAction, IProcessLoadedFileAction{

	private List fileItems;
	
	//Almacena el nombre de la propiedad que guarda el path a la imagen
	@Inject
	private String fileProperty;
	@Inject 
	private HashMap mapaComun;


	public void execute() throws Exception {
		Iterator i = getFileItems().iterator();
		while (i.hasNext()) {
			FileItem fi = (FileItem)i.next();
			String fileName = fi.getName();			
			if (!Is.emptyString(fileName)) {
				String propertyName = Strings.lastToken(getFileProperty(), ".");
				//Guardo en variable de sesion el fichero que se esta subiendo para guardarlo a posteriori
				mapaComun.put(FileEntityUtils.getSimpleModelName(getPreviousView()), fi);
				//Directorio unico para guardar
				String folder=UUID.randomUUID().toString();
				mapaComun.put(FileEntityUtils.getSimpleModelName(getPreviousView())+".folder",folder);
				mapaComun.put(FileEntityUtils.getSimpleModelName(getPreviousView())+".filename",fileName);
				//Pongo el nombre del fichero en la entidad
				findView().setValue(propertyName,folder+File.separator+fileName);
			
			}			
		}		
		closeDialog(); 
	}
	
	private View findView() { 
		String property = getFileProperty(); 
		String []m = property.split( "\\." );   
		View result = getPreviousView(); 
		for( int i = 0; i < m.length-1; i++ ) { 
			result = result.getSubview(m[i]); 
		} 		
		return result; 
	} 

	public String[] getNextControllers() {				
		return PREVIOUS_CONTROLLERS;
	}
	
	public String getCustomView() {		
		return PREVIOUS_VIEW;
	}
	
	public List getFileItems() {
		return fileItems;
	}

	public void setFileItems(List fileItems) {
		this.fileItems = fileItems;
	}

	public String getFileProperty() {
		return fileProperty;
	}

	public void setFileProperty(String fileProperty) {
		this.fileProperty = fileProperty;
	}
	

}
